package com.gz.gzmybatis.sqlsession;

import com.gz.entity.Monster;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class GzExecutor implements Executor {
    private  GzConfiguration configuration=new GzConfiguration();

    @Override
    public <T> T query(String sql, Object parameter) {
        //得到连接
        Connection connection = getConnection();
        //查询返回的结果集
        ResultSet resultSet = null;
        //PreparedStatement相比Statement可以防止sql注入
        PreparedStatement preparedStatement = null;

        try {
            preparedStatement = connection.prepareStatement(sql);
            //设置参数，如果参数多，可以使用数组处理
            preparedStatement.setString(1, parameter+"");
            resultSet = preparedStatement.executeQuery();
            //将结果集数据封装到对象中
            //完善的写法是反射机制
            Monster monster = new Monster();

            //遍历结果集
            while (resultSet.next()) {
                monster.setId(resultSet.getInt("id"));
                monster.setName(resultSet.getString("name"));
                monster.setAge(resultSet.getInt("age"));
                monster.setSalary(resultSet.getInt("salary"));
                monster.setEmail(resultSet.getString("email"));
                monster.setGender(resultSet.getInt("gender"));
                monster.setBirthday(resultSet.getDate("birthday"));
            }
            return (T) monster;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                if(resultSet!=null){
                    resultSet.close();
                }
                if(preparedStatement!=null){
                    preparedStatement.close();
                }
                if(connection!=null){
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private Connection getConnection() {
        Connection connection = configuration.build("gz-mybatis.xml");
        return connection;
    }
}
